package com.naiterui.ehp.bs.payment.controller;

import java.io.IOException;

import javax.validation.constraints.NotEmpty;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.naiterui.ehp.bp.bo.payment.NotifyBusinessRequestBO;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.payment.exception.ExceptionCodes;
import com.naiterui.ehp.bs.payment.exception.PaymentBusinessException;
import com.naiterui.ehp.bs.payment.service.INotifyBusinessService;
import com.naiterui.ehp.bs.payment.service.IRecoverNotifyBusinessService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import io.swagger.annotations.ApiOperation;

/**
 * 手动通知业务
 *
 * @author 王泽浩
 * @since 1.0.0
 */
@Slf4j
@Validated
@RestController
@AllArgsConstructor
public class NotifyBusinessController {

    private final INotifyBusinessService notifyBusinessService;
    private final IRecoverNotifyBusinessService recoverNotifyBusinessService;

    /**
     * 通知业务系统,此方法必须要在写库获取数据，防止读写数据库状态不一直，同步失败
     *
     * @param orderSn 订单号
     */
    @GetMapping("/notify/business/pay")
    public ResponseVO<Void> pay(@NotEmpty(message = "订单号不能为空") String orderSn) throws PaymentBusinessException {
        log.info("手动补发通知业务系统[支付回调通知] orderSn:{}", orderSn);
        this.notifyBusinessService.notifyBusinessPay(orderSn);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 退款通知业务系统
     *
     * @param refundOrderSn 退款单号
     */
    @GetMapping("/notify/business/refund")
    public ResponseVO<Void> refund(@NotEmpty(message = "退款单号不能为空") String refundOrderSn) {
        log.info("手动补发通知业务系统[退款回调通知] refundOrderSn:{}", refundOrderSn);
        this.notifyBusinessService.notifyBusinessRefund(refundOrderSn);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 定时任务调用接口，支付成功重试通知业务接口
     *
     * @param body 通知业务数据
     *
     * @return 调用成功
     *
     * @throws IOException 转换json异常
     */
    @PostMapping("/recover/notify")
    @ApiOperation(value = "定时任务调用接口，支付成功重试通知业务接口")
    public ResponseVO<Void> recoverNotify(@NotEmpty(message = "body数据不能为空") String body) {
        this.recoverNotifyBusinessService.asyncNotifyBusiness(JsonMapper.toObject(body, NotifyBusinessRequestBO.class));
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }
}
